package com.haixiaoke.saas.repository.util.timePair;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;

import java.time.DateTimeException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * 时间段比较工具
 */
public class TimePairCompareUtil {

    /**
     * 判断多个时间段是否有重叠（交集）
     *
     * @param timePairs 时间段数组
     * @param isStrict  是否严格重叠，true 严格，没有任何相交或相等；false 不严格，可以首尾相等，比如2023-05-29到2023-05-31和2023-05-31到2023-06-01，不重叠。
     * @return 返回是否重叠
     */
    public static boolean isOverlap(TimePair[] timePairs, boolean isStrict) {
        if (timePairs == null || timePairs.length == 0) {
            throw new DateTimeException("timePairs不能为空");
        }

        Arrays.sort(timePairs, Comparator.comparingLong(TimePair::getStart));

        for (int i = 1; i < timePairs.length; i++) {
            if (isStrict) {
                if (!(timePairs[i - 1].getEnd() < timePairs[i].getStart())) {
                    return true;
                }
            } else {
                if (!(timePairs[i - 1].getEnd() <= timePairs[i].getStart())) {
                    return true;
                }
            }
        }
        return false;
    }


    /**
     * 判断多个时间段是否有重叠（交集）
     * @param timePairList 时间段列表
     * @param isStrict 是否严格重叠，true 严格，没有任何相交或相等；false 不严格，可以首尾相等，比如2023-05-29到2023-05-31和2023-05-31到2023-06-01，不重叠。
     * @return 返回是否重叠
     */
    public static boolean isOverlap(List<TimePair> timePairList, boolean isStrict){
        if(CollectionUtil.isEmpty(timePairList)){
            throw new DateTimeException("TimePairList不能为空");
        }
        TimePair[] timePairs = new TimePair[timePairList.size()];
        timePairList.toArray(timePairs);
        return isOverlap(timePairs, isStrict);
    }


    public static void main(String[] args) {

        // 正在下单的
        String  timePair1Start = "2023-4-23 00:00:00";
        String timePair1End = "2023-4-25 23:59:59";

        long a1 = DateUtil.parse(timePair1Start).getTime();
        long a2 = DateUtil.parse(timePair1End).getTime();

        TimePair timePairA = new TimePair(a1, a2);


        // 已经租出去的时间段 list
        String  timePair2Start = "2023-5-25 00:00:00";
        String timePair2End = "2023-5-29 23:59:59";

        long b1 = DateUtil.parse(timePair2Start).getTime();
        long b2 = DateUtil.parse(timePair2End).getTime();

        // 下单了当时锁住了的. 方案1: redis存取  方案2: 放在mysql
        // 加锁: 吊起支付的时候加锁
        // 解锁: 1. 支付完成 2. 取消订单 3. 支付超时
        TimePair timePairB = new TimePair(b1, b2);


        List<TimePair> timePairList = new ArrayList<>();

        timePairList.add(timePairA);
        timePairList.add(timePairB);

        boolean overlap = TimePairCompareUtil.isOverlap(timePairList, true);
        System.out.println("overlap = " + overlap);


    }


}
